<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 slot="header" class="register-title">用户注册</h2>

      <el-form
          ref="registerForm"
          :model="form"
          :rules="rules"
          label-width="80px"
          class="register-form"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="passWord">
          <el-input
              v-model="form.passWord"
              type="password"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择用户类型">
            <el-option label="学生" value="2"></el-option>
            <el-option label="老师" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="register-btn"
              @click="handleRegister"
          >
            注册
          </el-button>
          <el-button
              type="text"
              @click="$router.push('/login')"
          >
            已有账号？去登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import userApi from '../api/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const registerForm = ref(null)

// 表单数据
const form = reactive({
  userName: '',
  passWord: '',

})

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, message: '密码长度不能少于3位', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

// 注册处理
const handleRegister = async () => {
  try {
    // 表单验证
    await registerForm.value.validate()

    // 发送注册请求
    const res = await userApi.register(form)

    if (res.code === 200) {
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error(error.message)
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  font-size: 20px;
}

.register-form {
  margin-top: 20px;
}

.register-btn {
  width: 100%;
  margin-bottom: 10px;
}
</style>